<template>
  <div class="backView" :style="{height: videoH + 'px'}">
    <div v-show="isAndroidDevice">
      <MAudioPlayerModel
        :audioPlayCurrentTime="audioPlayCurrentTime"
        :audioPlayDurationTime="audioPlayDurationTime"
        :getVideoData="getVideoData"
        :isPlayAudio="isPlayAudio"
        :audioPercentage="audioPercentage"
        @startPlayAudio="startPlayAudio"
        @touchEvent="touchEvent"
      ></MAudioPlayerModel>
    </div>

    <div v-show="!isAndroidDevice">
      <video id="hlsMediaObj"
             :height="videoH"
             :poster="coverImg"
             width="100%"
             muted
             x5-playsinline="true"
             ref="video"
             controls
             x5-video-player-type='h5'
             x5-video-player-fullscreen='true'
             playsinline
             webkit-playsinline
      ></video>
    </div>
  </div>
</template>

<script>
import course_api from '@/repo/api/course_api';
import { isAndroid, secondToDate } from '@/utils/util';
import MAudioPlayerModel from '@/components/MAudioPlayerModel';
import { Dialog, Toast } from 'vant';
import mixin from './mixins/index';

let Hls = null;
if (process.browser) {
  Hls = require('hls.js');
}

Vue.use(Dialog);
export default {
  name: 'playVideo',
  mixins: [mixin],
  props: ['getVideoData', 'coverImg', 'showPlayBtn', 'hasBuy', 'isFreeWatch'],
  components: {
    MAudioPlayerModel
  },
  data() {
    return {
      title: '视频详情',
      hlsPlayer: null,//H5播放器

      videoH: 202,
      isAndroidDevice: false,
      audioPercentage: 0,
      isPlayAudio: true,
      audioPlayCurrentTime: '0:00',
      audioPlayDurationTime: '00:00',
      isFirstPlay: true,
      isAndroidPlayVideo: false
    };
  },
  mounted() {
    this.videoH = document.documentElement.clientWidth * 9 / 16;

    this.hlsPlayer = document.getElementById('hlsMediaObj');
    this.hlsPlayer.addEventListener('timeupdate', this.videoTimeUpdate);
    this.hlsPlayer.addEventListener('ended', this.videoEnded);
    this.hlsPlayer.addEventListener('canplay', this.onCanplay);
    this.hlsPlayer.addEventListener('play', this.videoPlay);
  },
  watch: {
    getVideoData: {
      handler: function (val, oldVal) {

        if (val != oldVal) {
          this.isPlayAudio = false;
          setTimeout(() => {

            if (!this.courseId) return;

            if (this.isFirstPlay) {
              this.firstPlay();
              this.isFirstPlay = false;
            } else {
              this.playVideo();
            }
          }, 500);
        }
      },
      immediate: true,
      deep: true
    },
  },
  computed: {
    courseId: {
      get: function () {
        return this.$route.params.courseId;
      }
    }
  },
  methods: {
    videoPlay() {
      if (!this.isFreeWatch && this.hasBuy === 0) {
        this.hlsPlayer.pause();
      }
    },
    videoEnded() {
      this.isPlayAudio = false;
      this.canplay = false;
    },
    videoEndedAd() {
      setTimeout(() => {
        this.hlsPlayer.play();
      }, 500);
    },

    onCanplay() {
      this.canplay = true;

    },
    videoTimeUpdate() {
      let currentTime = this.hlsPlayer.currentTime;
      this.audioPercentage = (currentTime * 100 / this.hlsPlayer.duration).toFixed(0) * 1;
      this.audioPlayCurrentTime = secondToDate(currentTime);
      this.audioPlayDurationTime = secondToDate(this.hlsPlayer.duration);
    },
    firstPlay() {
      // 不能免费试看且未购买 则不会自动播放
      if (!this.isFreeWatch && this.hasBuy === 0) return this.hlsPlayer.pause();

      this.isFirstPlay && this.$emit('playBtnClick', this.isFirstPlay);

      // 原逻辑与播放逻辑重合，直接调用播放方法
      this.playVideo();
    },
    touchEvent(val) {
      let total = this.$refs.video.duration;
      if (this.$refs.video) {
        this.$refs.video.currentTime = val / 100 * total;
      }
    },
    startPlayAudio() {
      let element = document.getElementById('hlsMediaObj');
      if (this.isPlayAudio) {
        element.pause();
        this.isPlayAudio = false;
      } else {
        element.play();
        this.isPlayAudio = true;
      }
    },
    playVideo() {
      //android 手机播放音频兼容
      if (isAndroid && this.getVideoData.courseType === 2) {
        this.isAndroidDevice = true;
        this.isPlayAudio = true;
      } else {
        this.isAndroidDevice = false;
      }

      let playData = {
        courseType: this.getVideoData.courseType,
        mediaId: this.getVideoData.id,
        subjectId: this.courseId,
        courseId: this.getVideoData.courseId
      };

      course_api.playMedia(playData).then((res) => {
        if (res.resultCode == '0') {
          this.doSetMediaH5(res.responseData.m3u8url);
        }
      }).catch((error => console.log('error', error)));

    },
    doSetMediaH5(m3u8url) {
      // m3u8url = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8'
      if (process.env.NODE_ENV !== 'production') {
        m3u8url = 'https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8'
        m3u8url = 'http://player.alicdn.com/video/aliyunmedia.mp4'
        // m3u8url = '/web-hft-ee/static/opening.mp4';
      }

      this.hlsPlayer.src = m3u8url;
      // this.hlsPlayer.play();
      this.hlsPlayer.muted = false;
    },
    addPlayRecord() {
      let record = {
        courseId: this.getVideoData.courseId,
        type: this.getVideoData.courseType,
        id: this.getVideoData.id,
        subjectId: this.courseId
      };
      course_api.playRecord(record)
        .then((res) => {
          this.viewStatus = 0;
          this.requestNativeMethods('onJsWatchEURecord');
        })
        .catch((error => console.log('error', error)));
    }

  },
  destroyed() {
    document.getElementById('hlsMediaObj').src = null;
    this.hlsPlayer.removeEventListener('timeupdate', this.videoTimeUpdate, false);
    this.hlsPlayer.removeEventListener('ended', this.videoEnded, false);
    this.hlsPlayer.removeEventListener('canplay', this.onCanplay, false);
  }
};
</script>


<style scoped>
.backView {
  background-color: white;
  width: 100vw;
  overflow: hidden;

}

video {
  margin: 0px;
  padding: 0;
}

.coverBackView {
  width: 100%;
  position: relative;
}

.coverImg {
  width: 100%;
  object-fit: cover;
}

.playBtn {
  position: absolute;
  width: 48px;
  height: 48px;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;

}

/*.abcFix{*/
/*  position: fixed;*/
/*  top: 50%;*/
/*  left: 50%;*/
/*  width:100px;*/
/*  height: 100px;*/
/*  background: black;*/
/*  z-index: 200;*/
/*}*/
</style>
